package com.dxl.system.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxl.base.Result;
import com.dxl.base.Results;
import com.dxl.base.util.FileOperateUtil;
import com.dxl.system.mapper.ConfigMapper;
import com.dxl.system.mapper.GroupsMapper;
import com.dxl.system.mapper.NoteMapper;
import com.dxl.system.model.Config;
import com.dxl.system.model.Groups;
import com.dxl.system.model.Note;
import com.dxl.system.service.GroupsService;
import com.dxl.system.service.NoteService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <b> 分组服务接口实现类
 * </b><br><br><i>Description</i> :
 * <br>Date: 2019-09-25    <br>Author : dxl
 */
@Service
public class GroupsServiceImpl extends ServiceImpl<GroupsMapper,Groups> implements GroupsService {

    @Autowired(required = false)
    private GroupsMapper groupsMapper;
    @Autowired(required = false)
    private NoteMapper noteMapper;
    @Autowired(required = false)
    private NoteService noteService;
    @Autowired(required = false)
    private ConfigMapper configMapper;

    /**
     * <b> 插入分组
     * </b><br><br><i>Description</i> : 不能为空：组名称-group_name ；不能重复：组名称-group_name  
     * @param groups Groups
     * @return com.dxl.base.Result Groups
     * <br><br>Date: 2019-09-25    <br>Author : dxl
     */
    @Override
    public Result addOne(Groups groups) {
        Result result = isGroupsAddable(groups);
        boolean flag = (boolean) result.getData();
        if(!flag){
            return Results.failure(result.getMsg());
        }
        if(groups.getpId() == null){
            groups.setNote(groups.getGroupName()+"/");
        }else{
            Groups groups1 = groupsMapper.selectById(groups.getpId());
            groups.setNote(groups1.getNote()+groups.getGroupName()+"/");
        }
        QueryWrapper<Groups> wrapper = new QueryWrapper<>();
        wrapper.eq("note",groups.getNote());
        List<Groups> groupsList = groupsMapper.selectList(wrapper);
        if(groupsList.size() > 0){
            return Results.failure("此名称以前使用过，不能再使用:(");
        }
            groupsMapper.insert(groups);
        return Results.successWithData(groups);
    }

    /**
     * <b> 删除分组
     * </b><br><br><i>Description</i> : 
     * @param groupsIds List: Integer
     * @return com.dxl.base.Result int
     * <br><br>Date: 2019-09-25    <br>Author : dxl
     */
    @Override
    public Result delByIds(List<Integer> groupsIds) {
        int num = groupsMapper.deleteBatchIds(groupsIds);
        return Results.successWithData(num);
    }

    /**
     * <b> 删除分组及所有子分组和文件
     * </b><br><br><i>Description</i> :
     * @param groupsIds List: Integer
     * @return com.dxl.base.Result int
     * <br><br>Date: 2019-09-25    <br>Author : dxl
     */
    @Override
    @Transactional
    public Result delJoinByIds(List<Integer> groupsIds) {
        QueryWrapper<Groups> wrapper = new QueryWrapper<>();
        QueryWrapper<Config> configQueryWrapper = new QueryWrapper<>();
        configQueryWrapper.eq("config_key","FileRootPath");
        Config config = configMapper.selectOne(configQueryWrapper);
        if(config == null || config.getConfigKey() == null){
            return Results.failure("系统中无根路径配置，请在数据库中先配置config_key为FileRootPath的记录:(");
        }
        if(config.getConfigValue().substring(config.getConfigValue().length()-1).equals("/")){
            config.setConfigValue(config.getConfigValue().substring(0,config.getConfigValue().length()-1));
        }
        for(Integer id : groupsIds){
            Groups groups = groupsMapper.selectById(id);
            wrapper.eq("p_id",id);
            List<Groups> groupsList = groupsMapper.selectList(wrapper);
            List<Integer> groupsIds2 = groupsList.stream().map(Groups::getId).collect(Collectors.toList());
            if(groupsList != null && groupsList.size() > 0){
                delJoinByIds(groupsIds2);
            }

            QueryWrapper<Note> noteQueryWrapper = new QueryWrapper<>();
            noteQueryWrapper.eq("group_id",id);
            List<Note> noteList = noteMapper.selectList(noteQueryWrapper);
            List<Integer> noteIds = noteList.stream().map(Note::getId).collect(Collectors.toList());
            if(noteIds.size() > 0){
                noteService.delAndFile(noteIds);
            }
            FileOperateUtil.delAllFile(config.getConfigValue()+"/"+groups.getNote());
            File file = new File(config.getConfigValue()+"/"+groups.getNote());
            file.delete();
            groupsMapper.deleteById(id);
        }
        return Results.success();
    }

    /**
     * <b> 编辑分组
     * </b><br><br><i>Description</i> : 不能重复：组名称-group_name 
     * @param groups Groups
     * @return com.dxl.base.Result Groups
     * <br><br>Date: 2019-09-25    <br>Author : dxl
     */
    @Override
    public Result editOne(Groups groups) {
        Result result = isGroupsEditable(groups);
        boolean flag = (boolean) result.getData();
        if(!flag){
            return Results.failure(result.getMsg());
        }
        groupsMapper.updateById(groups);
        return Results.successWithData(groups);
    }

    /**
     * <b> ID查询分组
     * </b><br><br><i>Description</i> : 
     * @param groupsId Integer
     * @return com.dxl.base.Result: Groups
     * <br><br>Date: 2019-09-25    <br>Author : dxl
     */
    @Override
    public Result getById(Integer groupsId) {
        Groups groups = groupsMapper.selectById(groupsId);
        return Results.successWithData(groups);
    }

    /**
     * <b> 条件查询分组
     * </b><br><br><i>Description</i> : 
     * @param groups Groups
     * @return com.dxl.base.Result List: Groups
     * <br><br>Date: 2019-09-25    <br>Author : dxl
     */
    @Override
    public Result getList(Groups groups) {
        QueryWrapper<Groups> groupsWrapper = new QueryWrapper<Groups>(groups);
        List<Groups> groupsList = groupsMapper.selectList(groupsWrapper);
        return Results.successWithData(groupsList);
    }

    /**
     * <b> 分页条件查询分组
     * </b><br><br><i>Description</i> : 
     * @param groups Groups, currentPage -Integer, pageSize -Integer
     * @return com.dxl.base.Result List: Groups
     * <br><br>Date: 2019-09-25     <br>Author : dxl
     */
    @Override
    public Result getListByPage(Groups groups, Integer currentPage, Integer pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        List<Groups> groupsList = (List<Groups>) getList(groups).getData();
        PageInfo<Groups> pageInfo = new PageInfo<Groups>(groupsList);
        return Results.successWithData(pageInfo);
    }

    /**
     * <b> 模糊查询分组
     * </b><br><br><i>Description</i> : 模糊查询；模糊字段(模式：单字段)：全匹配：group_name-组名称 
     * @param groups Groups
     * @return com.dxl.base.Result List: Groups
     * <br><br>Date: 2019-09-25    <br>Author : dxl
     */
    @Override
    public Result getLikeGroups(Groups groups) {
        QueryWrapper<Groups> groupsWrapper = new QueryWrapper<>();
        if(groups.getGroupName() != null){
            groupsWrapper.like("group_name",groups.getGroupName());
        }else{
            return Results.failure("请正确填写属性:(");
        }
        List<Groups> groupsList = groupsMapper.selectList(groupsWrapper);
        return Results.successWithData(groupsList);
    }
    /**
     * <b> 分页模糊查询分组
     * </b><br><br><i>Description</i> : 模糊查询；模糊字段(模式：单字段)：全匹配：group_name-组名称 
     * @param groups Groups, currentPage -Integer, pageSize -Integer
     * @return com.dxl.base.Result List: Groups
     * <br><br>Date: 2019-09-25     <br>Author : dxl
     */
    @Override
    public Result getLikeGroupsByPage(Groups groups, Integer currentPage, Integer pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        List<Groups> groupsList = (List<Groups>) getLikeGroups(groups).getData();
        PageInfo<Groups> pageInfo = new PageInfo<Groups>(groupsList);
        return Results.successWithData(pageInfo);
    }

    /**
     * <b> 分组能否新增
     * </b><br><br><i>Description</i> : 不能为空：组名称-group_name ；不能重复：组名称-group_name  
     * @param groups Groups
     * @return com.dxl.base.Result boolean
     * <br><br>Date: 2019-09-25     <br>Author : dxl
     */
    @Override
    public Result isGroupsAddable(Groups groups) {

        if(groups.getGroupName() == null){
            return Results.successWithData(false,"组名称 不能为空:(");
        }

        if(groups.getGroupName() != null){
        QueryWrapper<Groups> groupsWrapper = new QueryWrapper<>();
        groupsWrapper.eq("group_name",groups.getGroupName());
        List<Groups> groupsList = groupsMapper.selectList(groupsWrapper);
            if(groupsList.size() > 0){
                return Results.successWithData(false,"组名称 重复:(");
            }
        }

        return Results.successWithData(true,"无重复:)");
    }

    /**
     * <b> 分组能否编辑
     * </b><br><br><i>Description</i> : 不能重复：组名称-group_name 
     * @param groups Groups
     * @return com.dxl.base.Result boolean
     * <br><br>Date: 2019-09-25     <br>Author : dxl
     */
    @Override
    public Result isGroupsEditable(Groups groups) {

        if(groups.getGroupName() != null){
            QueryWrapper<Groups> groupsWrapper1 = new QueryWrapper<>();
            groupsWrapper1.eq("id",groups.getId()).eq("group_name",groups.getGroupName());
            List<Groups> groupsList1 = groupsMapper.selectList(groupsWrapper1);
            QueryWrapper<Groups> groupsWrapper2 = new QueryWrapper<>();
            groupsWrapper2.eq("group_name",groups.getGroupName());
            List<Groups> groupsList2 = groupsMapper.selectList(groupsWrapper2);
            if(!((groupsList1.size() == 1 && groupsList2.size() == 1) ||(groupsList1.size() == 0 && groupsList2.size() == 0))){
                return Results.successWithData(false,"组名称 重复:(");
            }
        }

        return Results.successWithData(true,"无重复:)");
    }

    /**
     * <b> 获得树状目录
     * </b><br><br><i>Description</i> :
     * @return java.util.List<com.dxl.base.ZTreeNode>
     * <br><br>Date: 2019/9/26 16:07     <br>Author : dxl
     */
    @Override
    public List<Groups> getTree(Integer pId) {
        QueryWrapper<Groups> wrapper = new QueryWrapper<>();
        wrapper.eq("p_id",pId);
        List<Groups> groupsList = groupsMapper.selectList(wrapper);
        return groupsList;
    }

    /**
     * <b> 获得分组的所有父分组
     * </b><br><br><i>Description</i> : 第一个为pId为0的分组节点，最后一个为本节点
     * @param groupsId
     * @return com.dxl.base.Result
     * <br><br>Date: 2019/10/3 16:51    <br>Author : dxl
     */
    @Override
    public List<Groups> getParentGroups(Integer groupsId) {
        Groups groups = groupsMapper.selectById(groupsId);
        List<Groups> groupsList = new ArrayList<>();
        groupsList.add(groups);
        if(groups.getpId().equals(0)){
            return groupsList;
        }else {
            groupsList.addAll(getParentGroups(groups.getpId()));
        }
        return groupsList;
    }
}
